package com.kk.score.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.kk.score.dao.GradeDao;
import com.kk.score.entity.ConfigEntity;
import com.kk.score.entity.GradeEntity;
import com.kk.score.entity.TaskEntity;
import com.kk.score.entity.vo.GradeVo;
import com.kk.score.service.ConfigService;
import com.kk.score.service.GradeService;
import com.kk.score.utils.PageUtils;
import com.kk.score.utils.Query;
import com.kk.score.utils.R;
import com.kk.score.utils.SpringSecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.*;


/**
 * @author KK
 * @email 409592048@qq.com
 * @date 2022-11-02 12:28:00
 */
@RestController
@RequestMapping("/grade")
public class GradeController {

    @Autowired
    private GradeService gradeService;

    @Autowired
    private GradeDao gradeDao;

    @Autowired
    private ConfigService configService;

    /**
     * 列表
     */
    @GetMapping("/list")
    @PreAuthorize("hasAnyRole('ROLE_ADMIN')")
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = gradeService.queryPage(params);

        return R.ok().put("data", page);
    }

    /**
     * 列表
     */
    @GetMapping("/unitList")
    @PreAuthorize("hasAnyRole('ROLE_ADMIN')")
    public R unitList(@RequestParam Map<String, Object> params) {
        PageUtils page = gradeService.queryPageUnitList(params);

        return R.ok().put("data", page);
    }

    /**
     * 列表
     */
    @GetMapping("/personList")
    @PreAuthorize("hasAnyRole('ROLE_ADMIN')")
    public R personList(@RequestParam Map<String, Object> params) {
        PageUtils page = gradeService.queryPersonList(params);
        return R.ok().put("data", page);
    }


    /**
     * 打分
     */
    @PostMapping("/grade")
    @PreAuthorize("hasAnyRole('ROLE_USER')")
    public R grade(@RequestBody GradeEntity gradeEntity) {
        GradeEntity byId = gradeService.getById(gradeEntity.getUid());
        if (!byId.getUserUid().equals(SpringSecurityUtils.getUid())) {
            return R.error("非法操作！");
        }
        //判断次数是否用完
        if (byId.getCount() == 0) {
            return R.error("修改次数已用完！");
        }
        if (byId.getStatus() == 2) {
            return R.error("未在规定时间！");
        }
        int badCount = 0, sCount = 0;
        if (gradeEntity.getScore() == 1) {
            badCount++;
        } else if (gradeEntity.getScore() == 4) {
            sCount++;
        }
        int badC = Integer.parseInt(configService.getOne(new LambdaQueryWrapper<ConfigEntity>().eq(ConfigEntity::getStatus, 3)).getContext());
        int sC = Integer.parseInt(configService.getOne(new LambdaQueryWrapper<ConfigEntity>().eq(ConfigEntity::getStatus, 2)).getContext());
        //去数据库获取已评价的次数
        List<GradeVo> gradeAllByUser = gradeDao.findGradeAllByUser(SpringSecurityUtils.getUid());
        for (GradeVo gradeVo : gradeAllByUser) {
            if (gradeVo.getScore() == 1) {
                badCount++;
            }
            if (gradeVo.getScore() == 4) {
                sCount++;
            }
        }
        if (badCount > badC) {
            return R.error("不满意最多评价" + badC + "个单位！");
        }
        if (sCount > sC) {
            return R.error("非常满意最多评价" + sC + "个单位！");
        }
        Date date = new Date();
        byId.setCompleteTime(date);
        byId.setUpdateTime(date);
        byId.setScore(gradeEntity.getScore());
        byId.setStatus(1);
        byId.setCount(byId.getCount() - 1);
        byId.setContext(gradeEntity.getContext());
        gradeService.updateById(byId);
        return R.ok();
    }

    /**
     * 打分
     */
    @PostMapping("/gradeAll")
    @PreAuthorize("hasAnyRole('ROLE_USER')")
    public R gradeAll(@RequestBody Map<String, Object> map) {
        int badCount = 0, sCount = 0;
        Set<String> gradeUids = map.keySet();
        Collection<GradeEntity> grades = new ArrayList<>();
        for (String s : gradeUids) {
            String uid = s.split("-")[0];
            String todo = s.split("-")[1];
            if (todo.equals("score")) {
                int score = Integer.parseInt((String) map.get(uid + "-score"));
                if (score == 1) {
                    ++badCount;
                }
                if (score == 4) {
                    ++sCount;
                }
                grades.add(new GradeEntity(uid, (String) map.get(uid + "-context"), score, new Date(), 1));
            }
        }
        // 判断前端传来的是否为空置
        if (grades.size() == 0) {
            return R.error("请至少选择一个部门进行评价");
        }
        int badC = Integer.parseInt(configService.getOne(new LambdaQueryWrapper<ConfigEntity>().eq(ConfigEntity::getStatus, 3)).getContext());
        int sC = Integer.parseInt(configService.getOne(new LambdaQueryWrapper<ConfigEntity>().eq(ConfigEntity::getStatus, 2)).getContext());
        //去数据库获取已评价的次数
        List<GradeVo> gradeAllByUser = gradeDao.findGradeAllByUser(SpringSecurityUtils.getUid());
        for (GradeVo gradeVo : gradeAllByUser) {
            if (gradeVo.getScore() == 1) {
                badCount++;
            }
            if (gradeVo.getScore() == 4) {
                sCount++;
            }
        }
        if (badCount > badC) {
            return R.error("不满意最多评价" + badC + "个单位！");
        }
        if (sCount > sC) {
            return R.error("非常满意最多评价" + sC + "个单位！");
        }
        return R.ok().put("data", gradeService.updateBatchById(grades));
    }
}
